﻿#if UNITY_EDITOR
using System.Text.RegularExpressions;
/// <summary>
/// 编译写入块
/// </summary>
public class ESF_CSharpWriteCodeBlock : AbsESF_WriteBlock
{
    /// <summary>
    /// 块分类
    /// </summary>
    public override enESF_CompilerWriteBlockClassify classify { get { return enESF_CompilerWriteBlockClassify.CodeBlock; } }

    /// <summary>
    /// 语法规则
    /// </summary>
    public override enESF_CompilerWriteBlockSyntax syntax { get { return mSyntax; } }

    /// <summary>
    /// 等号代码规则
    /// </summary>
    const string mRegexEqualSignRule = @"<% *= *(.+?) *%>";
    /// <summary>
    /// 动态代码规则
    /// </summary>
    const string mRegexCodeRule = @"<%([\s|\S]+?)%>";
    /// <summary>
    /// using代码规则
    /// </summary>
    const string mRegexUsingRule = @"<% *= *(using +?.+?) *%>";

    /// <summary>
    /// 构造函数
    /// </summary>
    /// <param name="_originBlock">原始代码块</param>
    public ESF_CSharpWriteCodeBlock(string _originBlock)
        : base(_originBlock)
    {
    }

    /// <summary>
    /// 语法规则
    /// </summary>
    enESF_CompilerWriteBlockSyntax mSyntax = enESF_CompilerWriteBlockSyntax.ExecuteCode;
    /// <summary>
    /// 解析
    /// </summary>
    /// <param name="_originBlock">原始代码块</param>
    /// <returns>解析的代码块</returns>
    protected override string OnResolver(string _originBlock)
    {
        string result = string.Empty;
        if (OnIsMatch(_originBlock, mRegexUsingRule, out result))
        {//执行代码         
            mSyntax = enESF_CompilerWriteBlockSyntax.Using;
        }
        else if (OnIsMatch(_originBlock, mRegexEqualSignRule, out result))
        {//=号赋值        
            mSyntax = enESF_CompilerWriteBlockSyntax.EqualSignSssignment;
        }
        else if (OnIsMatch(_originBlock, mRegexCodeRule, out result))
        {//执行代码         
            mSyntax = enESF_CompilerWriteBlockSyntax.ExecuteCode;
        }        
        else
        {//内联函数
            mSyntax = enESF_CompilerWriteBlockSyntax.InlineFunction;
        }
        return result;
    }

    /// <summary>
    /// 是否匹配指定的规则
    /// </summary>
    /// <param name="_originBlock">原始代码块</param>
    /// <param name="_rule">规则</param>
    /// <param name="_result">结果</param>
    /// <returns>true:匹配规则 ,false:不匹配规则</returns>
    bool OnIsMatch(string _originBlock, string _rule, out string _result)
    {
        _result = string.Empty;
        Match match = Regex.Match(_originBlock, _rule);
        if (match.Success)
        {
            _result = match.Groups[1].Value;
        }
        return match.Success;
    }

    /// <summary>
    /// 获得代码块
    /// </summary>
    /// <param name="_resultCodeBlock">结果代码块</param>
    /// <returns>代码块</returns>
    protected override string OnGetCode(string _resultCodeBlock) {
        return _resultCodeBlock;
    }
}
#endif